package com.ybf.api.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.Map;

@Data
public class WsMessage<T> {
    private String type;
    private T data;
    private Integer status;

    static public String HEARTBEAT = "heartbeat";
    static public String CHAT = "data";
    static public String LOGIN = "login";

    static public <T>WsMessage ok(String type, T data) {
        WsMessage wsMessage = new WsMessage();
        wsMessage.setType(type);
        wsMessage.setData(data);
        wsMessage.setStatus(200);
        return wsMessage;
    }

    static public WsMessage error(String type, Map data) {
        WsMessage wsMessage = new WsMessage();
        wsMessage.setType(type);
        wsMessage.setData(data);
        wsMessage.setStatus(500);
        return wsMessage;
    }

    static public WsMessage Heartbeat() {
        return WsMessage.ok(WsMessage.HEARTBEAT, null);
    }

    @JsonIgnore
    public boolean isEmpty() {
        return type == null;
    }

    public static WsMessage parse(String json) {
        // jackson json转对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, WsMessage.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public String toString() {
        // jackson 对象转json
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
